package com.wuyou.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){

        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        Map<String,String> map = new LinkedMap();
        //放过的路径       固定单词
//        map.put("/index","anon");
        map.put("/userLogin/**","anon");
//        map.put("/js/**","anon");
        //有权限才能访问    固定单词加声明 声明自定义
//        map.put("/person/toPerson","perms[person-list]");
//        map.put("/role/toRole","perms[person-list]");
//        map.put("/menu/toZTree","perms[person-list]");
//        map.put("/person/examin","perms[person-examin]");
//        map.put("/role/addIndex","perms[role-add]");
        //拦截是路径    固定单词
        map.put("/**","authc");

        filterFactoryBean.setFilterChainDefinitionMap(map);
        //跳转到登录页
        filterFactoryBean.setLoginUrl("/login/toLogin");
        //没权限时的默认页面
        filterFactoryBean.setUnauthorizedUrl("/login/unauthorized");

        return filterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(loginRealm);
         return defaultWebSecurityManager;
    }

    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher) {
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }

    //解密方法与逻辑
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(3);
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;

    }


    //权限控制到按钮
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

}


